package com.learning.android.currencyconvertor;



import java.text.DecimalFormat;
import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;




public class CurrencyListAdapter extends BaseAdapter {
	
	
	private CurrencyConvertor parentListActivity;
	private ListView parentListView;
	private ArrayList<CurrencyXchgRatePair> currArrayList;
	private LayoutInflater currInflator;
	private Cursor currList;
	private CurrencySelectItem  currencySelectItem;
	private CurrencyDBAdapter currDBAdapter;
	private boolean flagTextChangeFromUser = false;
	private DecimalFormat df = new DecimalFormat("#.####");
	
	
	
	
	//Currency Swap Button OnClick Listener
	private  OnClickListener currSwapOnClickListener = new OnClickListener()
	{
		
		@Override
		public void onClick(View v) {
			
			int pos = parentListView.getPositionForView(v);
			currArrayList.get(pos).setDirection(!currArrayList.get(pos).isDirection());
			
			Animation anim = AnimationUtils.loadAnimation(v.getContext(), R.anim.convertor_rotate_action);
			try{
			anim.setAnimationListener(new AnimationListener()
				{

					@Override
					public void onAnimationEnd(Animation animation) {
						// TODO Auto-generated method stub
						notifyDataSetChanged();

					}

					@Override
					public void onAnimationRepeat(Animation animation) {
						// TODO Auto-generated method stub
						
					}

					@Override
					public void onAnimationStart(Animation animation) {
						// TODO Auto-generated method stub
						
					}
				}
			);
			} catch(Exception e)
			{
				System.out.println("OnClick Exception "+e.toString());
			}
			
			v.startAnimation(anim);

		}
	};
	
	private OnItemSelectedListener currSpinnerItemSelectedListener = new OnItemSelectedListener()
	{

		@Override
		public void onItemSelected(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			if(view!=null)
			{
				int previous;
				int pos = parentListView.getPositionForView(parent);
				CurrencyXchgRatePair currencyXchgRatePair = currArrayList.get(pos);
				//System.out.println("Item Selected Listener: "+parent + " - "+ view+" - "+ position+ " - "+id );
				switch(parent.getId())
			    {
				case R.id.fromCurrency:
					previous = currencyXchgRatePair.isDirection()?currencyXchgRatePair.getToCurrID():currencyXchgRatePair.getFromCurrID();
					if(previous != (position + 1))
					{
						if(!currencyXchgRatePair.isDirection())
						{
						    currencyXchgRatePair.setFromCurrID(position + 1);
						}
						else
						{
							currencyXchgRatePair.setToCurrID(position + 1);
						}
						
						if(currDBAdapter.getNewCurrencyPair(currencyXchgRatePair)==null)
						{
							System.out.println("Currency Convertor Pair Is not updated");
						}
						
						notifyDataSetChanged();
					}
				    
				break;
				case R.id.toCurrency:
					previous = (!currencyXchgRatePair.isDirection())?currencyXchgRatePair.getToCurrID():currencyXchgRatePair.getFromCurrID();
					if( previous != (position + 1))
					{
						if(!currencyXchgRatePair.isDirection())
						{
						    currencyXchgRatePair.setToCurrID(position + 1);
						}
						else
						{
							currencyXchgRatePair.setFromCurrID(position + 1);
						}
						if(currDBAdapter.getNewCurrencyPair(currencyXchgRatePair)==null)
						{
							System.out.println("Currency Convertor Pair Is not updated");
						}
						
						notifyDataSetChanged();
					}
					
				default:
			    break;
				}
			}
			
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
			
		}
		
	};

	
	
	// From Currency Edit Text OnKey Listener
	private class FromCurrTextWatcher implements TextWatcher{
		
		private EditText v = null;
		private int pos;
		public FromCurrTextWatcher(EditText view)
		{
			v = view;
		}

		@Override
		public void afterTextChanged(Editable s) {
			}


		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub
			//System.out.println("Triggere Here!");
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// TODO Auto-generated method stub
			// TODO Auto-generated method stub
			if(!flagTextChangeFromUser)
			{
				//System.out.println("From Currency Edit Text Changed ");
				flagTextChangeFromUser = true;
			 try{
				 
				//System.out.println("Position at " + parentListView.getPositionForView((View) v)  + " Content " + v.getText() + " Position at ");
				pos = parentListView.getPositionForView((View) v);
				
				if(v.getText().toString()!=null)
				currArrayList.get(pos).setFromCurrAMT(Float.valueOf((v.getText().toString())));
				
				if(currArrayList.get(pos).getToCurrAMT()!=1)
				currArrayList.get(pos).setToCurrAMT(1);
				
				((EditText)((LinearLayout)v.getParent()).getChildAt(2)).setText(df.format(
						Float.valueOf(v.getText().toString())*
						 (currArrayList.get(pos).isDirection()? 
						  currArrayList.get(pos).getRateREV():
							  currArrayList.get(pos).getRateADV())));
				
				//notifyDataSetChanged();		
			    } catch(Exception e)
				{
					System.out.println(" EditText Exception happened "+e.toString());
				}
			    flagTextChangeFromUser = false;
			}
		}
	}
	
	
	
	//To Currency Edit Text OnKey Listener
	private class ToCurrTextWatcher implements TextWatcher{
		
		private EditText v = null;
		private int pos;
		
		public ToCurrTextWatcher(EditText view)
		{
			v = view;
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			
			
			// TODO Auto-generated method stub
	    if(!flagTextChangeFromUser)
	    {
	    	//System.out.println("To Currency Rate EditText Changed! ");
		    	flagTextChangeFromUser = true;
			 try{ 
				 System.out.println("Position at " + parentListView.getPositionForView((View) v)  + " Content " + v.getText() + " Position at " );
				 pos = parentListView.getPositionForView((View) v);
				 
				 if(v.getText().toString()!=null)
					currArrayList.get(pos).setToCurrAMT(Float.valueOf(v.getText().toString()));
				 
				 
				 if(currArrayList.get(pos).getFromCurrAMT()!=1)
				    currArrayList.get(pos).setFromCurrAMT(1);
				
				
				 ((EditText)((LinearLayout)v.getParent()).getChildAt(0)).setText(df.format(
							Float.valueOf(v.getText().toString())*
							 (currArrayList.get(pos).isDirection()? 
							  currArrayList.get(pos).getRateADV():
								  currArrayList.get(pos).getRateREV())));
				   
				} catch(Exception e)
				{
					System.out.println(" EditText Exception happened "+e.toString());
				}
				flagTextChangeFromUser = false;
	        }
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub
			System.out.println("Before Change To Currency Exchange ");
		}

		@Override
		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub
			
		}
		
	}


	
	public CurrencyListAdapter (Cursor currencyList,CurrencyConvertor currListActivity, CurrencyDBAdapter currencyDBAdapter)
	{
		//Debug
		System.out.println("Initializing List Adapter...");
		
		currList = currencyList;
		currInflator = (LayoutInflater)currListActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		parentListActivity =  currListActivity;
		parentListView = parentListActivity.getListView();
		currDBAdapter = currencyDBAdapter;
		currArrayList = new ArrayList<CurrencyXchgRatePair>();
		
		//Initialise ArrayList
		copyCursor2ArrayList(currList);
	}

	/**
	 * Copy All the Values from Cursor to Array List
	 * @param currList Cursor have data from database
	 * @param currArrayList
	 */
	public void copyCursor2ArrayList(Cursor currList) {
		currArrayList.removeAll(currArrayList);
		// TODO Auto-generated method stub
		for(int i =0 ; i < currList.getCount();i++)
		{
			CurrencyXchgRatePair currencyXchgRatePair = new CurrencyXchgRatePair();
			//Initialize Currencies Xchg Rate Array List
			currList.moveToPosition(i);
			currencyXchgRatePair.setCursorRowID(i);
			currencyXchgRatePair.setDbRowID(currList.getInt(currList.getColumnIndex(CurrencyDBAdapter.KEY_ID)));
			currencyXchgRatePair.setFromCurrAMT(currList.getFloat(currList.getColumnIndex(CurrencyDBAdapter.KEY_FROM_CURR_AMT)));
			currencyXchgRatePair.setToCurrAMT(currList.getFloat(currList.getColumnIndex(CurrencyDBAdapter.KEY_TO_CURR_AMT)));
			currencyXchgRatePair.setFromCurrID(currList.getInt(currList.getColumnIndex(CurrencyDBAdapter.KEY_FROM_CURR_ID)));
			currencyXchgRatePair.setToCurrID(currList.getInt(currList.getColumnIndex(CurrencyDBAdapter.KEY_TO_CURR_ID)));
			currencyXchgRatePair.setRateADV(currList.getFloat(currList.getColumnIndex(CurrencyDBAdapter.KEY_RATE_ADV)));
			currencyXchgRatePair.setRateREV(currList.getFloat(currList.getColumnIndex(CurrencyDBAdapter.KEY_RATE_REV)));
			currencyXchgRatePair.setSelection(currList.getInt(currList.getColumnIndex(CurrencyDBAdapter.KEY_SELECTION)));
			currencyXchgRatePair.setDirection(currList.getInt(currList.getColumnIndex(CurrencyDBAdapter.KEY_DIRECTION))>0);
			
			currArrayList.add(currencyXchgRatePair);
		}
	}
	
	/**
	 * Update Data in Database According to ArrayList
	 * 
	 */
	public void updateDBAsArrayList()
	{
		for(int i =0;i<currArrayList.size();i++)
		{
			currDBAdapter.updateXchgRate(currArrayList.get(i).getDbRowID(),
					                     0, //Currency Exchange Rate will not be updated in database
					                     0, //Currency Exchange Rate will not be updated in database
					                     currArrayList.get(i).getSelection(),
					                     currArrayList.get(i).isDirection()==false?0:1,
					                     currArrayList.get(i).getFromCurrAMT(),
					                     currArrayList.get(i).getToCurrAMT());
		}
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		//return currList.getCount();
		return currArrayList.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		//return currList.moveToPosition(position);
		return currArrayList.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}



	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		
		//System.out.println("Current Position is at " + position);
		
		//New Created Convert View
//		if(convertView == null)
//		{
			convertView = currInflator.inflate(R.layout.item_currency_selected, null);
			currencySelectItem = new CurrencySelectItem();
			
			//Get View in CurrencySelectItem.xml by ID
			currencySelectItem.fromCurrSpinner = (Spinner)convertView.findViewById(R.id.fromCurrency);
			currencySelectItem.toCurrSpinner = (Spinner)convertView.findViewById(R.id.toCurrency);
			currencySelectItem.fromCurrRate = (EditText)convertView.findViewById(R.id.fromCurrRate);
			currencySelectItem.toCurrRate = (EditText)convertView.findViewById(R.id.toCurrRate);
			currencySelectItem.currencySwapBtn = (Button)convertView.findViewById(R.id.swap);
			//currencySelectItem.versus = (TextView)convertView.findViewById(R.id.versus);
			
			//Set OnClick Listener for Currency Swap Button
			currencySelectItem.currencySwapBtn.setOnClickListener(currSwapOnClickListener);
			currencySelectItem.fromCurrSpinner.setOnItemSelectedListener(currSpinnerItemSelectedListener);
			currencySelectItem.toCurrSpinner.setOnItemSelectedListener(currSpinnerItemSelectedListener);
			
			//Set up Adapter for Spinner
			currencySelectItem.setUpAdapterForSpinner(parentListActivity,currDBAdapter);
			
			//Populate the currency xchgrates for each item
			fillView(currencySelectItem,position); 
			
			//Attached a tag to it for easy reference later
			convertView.setTag(currencySelectItem);
			
//		}
//		else 
//		{
//			//Recycled Convert View
//			currencySelectItem = (CurrencySelectItem)convertView.getTag();
//			
//			//Remove the Text Change Listener
//			currencySelectItem.fromCurrRate.removeTextChangedListener(currencySelectItem.fromCurrTextWatcher);
//			currencySelectItem.toCurrRate.removeTextChangedListener(currencySelectItem.toCurrTextWatcher);
//			
//			fillView(currencySelectItem,position);
//			
//		}
	    
		return convertView;
	}

	//Binding Cursor to Spinner and EditText in CurrencySelectItem.XML
	private void fillView(CurrencySelectItem currencySelectItem,int position) {
		// TODO Auto-generated method stub
		
		try{
			System.out.println("System Select Item Value "+ (currencySelectItem==null));
	    if(currArrayList.get(position).isDirection()== false)
	    {
	    
	    currencySelectItem.toCurrSpinner.setSelection(currArrayList.get(position).getToCurrID()-1);
	    currencySelectItem.fromCurrSpinner.setSelection(currArrayList.get(position).getFromCurrID()-1);
	    
		    if(currArrayList.get(position).getToCurrAMT()==1)
		    {
			    currencySelectItem.fromCurrRate.setText(df.format(currArrayList.get(position).getFromCurrAMT()));
			    currencySelectItem.toCurrRate.setText(df.format(currArrayList.get(position).getRateADV()*currArrayList.get(position).getFromCurrAMT()));
	        }
		    else
		    {
		    	currencySelectItem.fromCurrRate.setText(df.format(currArrayList.get(position).getRateREV()*currArrayList.get(position).getToCurrAMT()));
		    	currencySelectItem.toCurrRate.setText(df.format(currArrayList.get(position).getToCurrAMT()));
		    }
	    }
	    else
	    {
	    
    	currencySelectItem.fromCurrSpinner.setSelection(currArrayList.get(position).getToCurrID()-1);
  	    currencySelectItem.toCurrSpinner.setSelection(currArrayList.get(position).getFromCurrID()-1);
  	    
	  	    if(currArrayList.get(position).getToCurrAMT()==1)
	  	    {
		  	    currencySelectItem.fromCurrRate.setText(df.format(currArrayList.get(position).getFromCurrAMT()));
		  	    currencySelectItem.toCurrRate.setText(df.format(currArrayList.get(position).getRateREV()*currArrayList.get(position).getFromCurrAMT()));
		  	}
	  	    else
	  	    {
	  	    	currencySelectItem.fromCurrRate.setText(df.format(currArrayList.get(position).getRateADV()*currArrayList.get(position).getToCurrAMT()));
		  	    currencySelectItem.toCurrRate.setText(df.format(currArrayList.get(position).getToCurrAMT()));
	  	    }

	    }
	    //currencySelectItem.currListAdapter.notifyDataSetChanged();

	    //Set TextChange Listener for from currency exchange rate
		currencySelectItem.fromCurrTextWatcher = new FromCurrTextWatcher(currencySelectItem.fromCurrRate); 
		currencySelectItem.fromCurrRate.addTextChangedListener(currencySelectItem.fromCurrTextWatcher);
		
		
		//Set TextChange Listener for Text Field of to currency exchange rate
		currencySelectItem.toCurrTextWatcher = new ToCurrTextWatcher(currencySelectItem.toCurrRate);
		currencySelectItem.toCurrRate.addTextChangedListener(currencySelectItem.toCurrTextWatcher);
		} catch(Exception e)
		{
			System.out.println(" Fill View Exception "+ e.toString());
		}
	}
	
}
